<template>
  <div class="practice-graph">
    <!-- 主练习章节界面 -->
    <div v-if="!showQuestionPractice && !showSmartRoll && !showScore">
      <div class="header-section">
        <h1>{{ currentCourse }} 练习题库</h1>
        <div class="search-filter">
          <button class="smart-roll-btn" @click="smartRoll">
            智能组卷
          </button>
        </div>
      </div>
      <div class="table-container">
        <table>
          <thead>
            <tr>
              <th>章节名称</th>
              <th>题目数量</th>
              <th>选择题</th>
              <th>判断题</th>
              <th>创新实践</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="chapter in filteredChapters" :key="chapter.name">
              <td>{{ chapter.name }}</td>
              <td>{{ chapter.total }}</td>
              <td>{{ chapter.choice }}</td>
              <td>{{ chapter.judgment }}</td>
              <td>{{ chapter.creative }}</td>
              <td>
                <button 
                  class="practice-btn"
                  @click="startChapterPractice(chapter)"
                >
                  <i class="material-icons">play_arrow</i>开始练习
                </button>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </div>
    <!-- 智能组卷界面 -->
    <div class="smart-roll" v-if="showSmartRoll && !showScore">
      <div class="header-section">
        <button class="back-btn" @click="backToChapters">
          <i class="material-icons">arrow_back</i>
        </button>
        <h1>智能组卷</h1>
        <div class="practice-stats">
          第 {{ currentSmartRollIndex + 1 }} 题/共 {{ smartRollQuestions.length }} 题
        </div>
      </div>
      
      <div class="question-container">
        <div class="question-card">
          <div class="question-meta">
            <span class="question-type">{{ currentSmartRollQuestion.type }}</span>
            <span class="question-difficulty" :class="currentSmartRollQuestion.difficulty.toLowerCase()">
              {{ currentSmartRollQuestion.difficulty }}
            </span>
          </div>
          <div class="question-title">{{ currentSmartRollQuestion.title }}</div>
          <div class="question-stem">{{ currentSmartRollQuestion.stem }}</div>
          <!-- 选择题选项 -->
          <div class="question-options" v-if="currentSmartRollQuestion.type === '单选题' || currentSmartRollQuestion.type === '多选题'">
            <div 
              class="option" 
              v-for="(option, index) in currentSmartRollQuestion.options" 
              :key="index"
              @click="selectSmartRollOption(index)"
              :class="{
                selected: smartRollUserAnswers.includes(index),
                correct: showSmartRollAnswer && currentSmartRollQuestion.answer.includes(index.toString()),
                incorrect: showSmartRollAnswer && smartRollUserAnswers.includes(index) && !currentSmartRollQuestion.answer.includes(index.toString())
              }"
            >
              <span class="option-letter">{{ String.fromCharCode(65 + index) }}.</span>
              <span class="option-text">{{ option }}</span>
            </div>
          </div>
          <!-- 判断题选项 -->
          <div class="judgment-options" v-if="currentSmartRollQuestion.type === '判断题'">
            <button 
              class="judgment-btn true-btn"
              :class="{
                selected: smartRollUserAnswers[0] === 'true',
                correct: showSmartRollAnswer && currentSmartRollQuestion.answer === 'true',
                incorrect: showSmartRollAnswer && smartRollUserAnswers[0] === 'true' && currentSmartRollQuestion.answer !== 'true'
              }"
              @click="selectSmartRollJudgment('true')"
            >
              正确
            </button>
            <button 
              class="judgment-btn false-btn"
              :class="{
                selected: smartRollUserAnswers[0] === 'false',
                correct: showSmartRollAnswer && currentSmartRollQuestion.answer === 'false',
                incorrect: showSmartRollAnswer && smartRollUserAnswers[0] === 'false' && currentSmartRollQuestion.answer !== 'false'
              }"
              @click="selectSmartRollJudgment('false')"
            >
              错误
            </button>
          </div>
          <!-- 创新实践题 -->
          <div class="creative-answer" v-if="currentSmartRollQuestion.type === '创新实践'">
            <textarea 
              v-model="smartRollCreativeAnswer" 
              placeholder="请在此输入您的创新想法..."
              class="creative-textarea"
            ></textarea>
          </div>
          <!-- 反馈信息 -->
          <div v-if="showSmartRollAnswer" class="answer-feedback" :class="{ correct: smartRollAnswerCorrect, incorrect: !smartRollAnswerCorrect }">
            {{ smartRollAnswerFeedback }}
          </div>
          <!-- 答案解析 -->
          <div class="answer-analysis" v-if="showSmartRollAnswer && currentSmartRollQuestion.analysis">
            <div class="analysis-title">解析：</div>
            <div class="analysis-content">{{ currentSmartRollQuestion.analysis }}</div>
          </div>
          <div class="practice-actions">
            <button 
              class="submit-btn" 
              @click="checkSmartRollAnswer"
              v-if="!showSmartRollAnswer"
              :disabled="!canSubmitSmartRoll"
            >
              提交答案
            </button>
            <button 
              class="next-btn" 
              @click="nextSmartRollQuestion"
              v-if="showSmartRollAnswer"
            >
              {{ isLastSmartRollQuestion ? '完成练习' : '下一题' }}
            </button>
          </div>
        </div>
      </div>
    </div>
    <!-- 得分情况界面 -->
    <div class="score-container" v-if="showScore">
      <div class="score-card">
        <h2>测试结果</h2>
        <div class="score-main">
          <div class="score-circle">
            <div class="score-value">{{ score.actualScore }}/{{ score.totalScore }}</div>
            <div class="score-percentage">{{ score.percentage }}%</div>
            <div class="score-per-question">每题分数: {{ score.scorePerQuestion }}分</div>
          </div>
          <div class="score-details">
            <div class="detail-item">
              <span class="detail-label">正确：</span>
              <span class="detail-value correct">{{ score.correctCount }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">错误：</span>
              <span class="detail-value incorrect">{{ score.incorrectCount }}</span>
            </div>
            <div class="detail-item">
              <span class="detail-label">用时：</span>
              <span class="detail-value">{{ formatTime(score.timeSpent) }}</span>
            </div>
          </div>
        </div>
        <button class="restart-btn" @click="restartSmartRoll">重新测试</button>
        <button class="back-home-btn" @click="backToChapters">返回首页</button>
      </div>
      <!-- 错题分析部分 -->
      <div class="mistakes-section" v-if="score.wrongQuestions.length > 0">
        <h3>错题分析</h3>
        <div class="mistake-item" v-for="(q, idx) in score.wrongQuestions" :key="'mistake-'+idx">
          <div class="mistake-header">
            <span class="mistake-index">题目 {{ idx + 1 }}</span>
          </div>
          <div class="mistake-content">
            <div class="mistake-question">{{ q.stem }}</div>
            <div class="mistake-answer">
              <span class="wrong-answer">你的答案: {{ formatUserAnswer(q.userAnswer, q.type) }}</span>
              <span class="correct-answer">正确答案: {{ formatCorrectAnswer(q) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 具体章节练习界面 -->
    <div class="question-practice" v-else-if="showQuestionPractice">
      <div class="header-section">
        <button class="back-btn" @click="backToChapters">
          <i class="material-icons">arrow_back</i>
        </button>
        <h1>{{ currentChapter }} - 创新练习</h1>
        <div class="practice-stats">
          第 {{ currentQuestionIndex + 1 }} 题/共 {{ currentQuestions.length }} 题
        </div>
      </div>

      <div class="question-container">
        <div class="question-card">
          <div class="question-meta">
            <span class="question-type">{{ currentQuestion.type }}</span>
            <span class="question-difficulty" :class="currentQuestion.difficulty.toLowerCase()">
              {{ currentQuestion.difficulty }}
            </span>
          </div>
          <div class="question-title">{{ currentQuestion.title }}</div>
          <div class="question-stem">{{ currentQuestion.stem }}</div>

          <!-- 选择题选项 -->
          <div class="question-options" v-if="currentQuestion.type === '单选题' || currentQuestion.type === '多选题'">
            <div 
              class="option" 
              v-for="(option, index) in currentQuestion.options" 
              :key="index"
              @click="selectOption(index)"
              :class="{
                selected: userAnswers.includes(index),
                correct: showAnswer && currentQuestion.answer.includes(index.toString()),
                incorrect: showAnswer && userAnswers.includes(index) && !currentQuestion.answer.includes(index.toString())
              }"
            >
              <span class="option-letter">{{ String.fromCharCode(65 + index) }}.</span>
              <span class="option-text">{{ option }}</span>
            </div>
          </div>

          <!-- 判断题选项 -->
          <div class="judgment-options" v-if="currentQuestion.type === '判断题'">
            <button 
              class="judgment-btn true-btn"
              :class="{
                selected: userAnswers[0] === 'true',
                correct: showAnswer && currentQuestion.answer === 'true',
                incorrect: showAnswer && userAnswers[0] === 'true' && currentQuestion.answer !== 'true'
              }"
              @click="selectJudgment('true')"
            >
              正确
            </button>
            <button 
              class="judgment-btn false-btn"
              :class="{
                selected: userAnswers[0] === 'false',
                correct: showAnswer && currentQuestion.answer === 'false',
                incorrect: showAnswer && userAnswers[0] === 'false' && currentQuestion.answer !== 'false'
              }"
              @click="selectJudgment('false')"
            >
              错误
            </button>
          </div>

          <!-- 创新实践题 -->
          <div class="creative-answer" v-if="currentQuestion.type === '创新实践'">
            <textarea 
              v-model="creativeAnswer" 
              placeholder="请在此输入您的创新想法..."
              class="creative-textarea"
            ></textarea>
          </div>

          <!-- 反馈信息 -->
          <div v-if="showAnswer" class="answer-feedback" :class="{ correct: answerCorrect, incorrect: !answerCorrect }">
            {{ answerFeedback }}
          </div>

          <!-- 答案解析 -->
          <div class="answer-analysis" v-if="showAnswer && currentQuestion.analysis">
            <div class="analysis-title">解析：</div>
            <div class="analysis-content">{{ currentQuestion.analysis }}</div>
          </div>

          <div class="practice-actions">
            <button 
              class="submit-btn" 
              @click="checkAnswer"
              v-if="!showAnswer"
              :disabled="!canSubmit"
            >
              提交答案
            </button>
            <button 
              class="next-btn" 
              @click="nextQuestion"
              v-if="showAnswer"
            >
              {{ isLastQuestion ? '完成练习' : '下一题' }}
            </button>
          </div>
        </div>
      </div>
    </div>
  </div>
    <!-- 练习总结弹窗 --> 
    <div class="summary-modal" v-if="showSummary"> 
      <div class="modal-overlay" @click="showSummary = false"></div> 
      <div class="modal-content"> 
        <h2>练习完成!</h2> 
        <div class="stats-container"> 
          <div class="stat-item"> 
            <div class="stat-value">{{ score.actualScore }}分</div> 
            <div class="stat-label">得分</div> 
          </div> 
          <div class="stat-item"> 
            <div class="stat-value">{{ formatTime(score.timeSpent) }}</div> 
            <div class="stat-label">用时</div> 
          </div> 
          <div class="stat-item"> 
            <div class="stat-value">{{ score.correctCount }}/{{ score.totalCount }}</div> 
            <div class="stat-label">正确数</div> 
          </div> 
        </div> 
        
        <div class="mistakes-section" v-if="score.wrongQuestions.length > 0"> 
          <h3>错题分析</h3> 
          <div 
            class="mistake-item" 
            v-for="(q, idx) in score.wrongQuestions" 
            :key="'mistake-'+idx" 
          > 
            <div class="mistake-question">{{ q.stem }}</div> 
            <div class="mistake-answer"> 
              <span class="wrong-answer">你的答案: {{ formatUserAnswer(q.userAnswer, q.type) }}</span> 
              <span class="correct-answer">正确答案: {{ formatCorrectAnswer(q) }}</span> 
            </div> 
          </div> 
        </div> 
        
        <div class="modal-actions"> 
          <button class="action-btn review-btn" @click="reviewWrongQuestions" v-if="score.wrongQuestions.length > 0"> 
            复习错题 
          </button> 
          <button class="action-btn finish-btn" @click="finishAndReturn"> 
            完成练习 
          </button> 
        </div> 
      </div> 
    </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRoute } from 'vue-router'

const route = useRoute()
const currentCourse = ref('思维创新与开发')
const searchQuery = ref('')
const showQuestionPractice = ref(false)
const showSmartRoll = ref(false)
const showScore = ref(false)
const currentChapter = ref('')
const currentQuestions = ref([])
const currentQuestionIndex = ref(0)
const userAnswers = ref([])
const showAnswer = ref(false)
const answerCorrect = ref(false)
const creativeAnswer = ref('')

// 智能组卷相关状态
const smartRollQuestions = ref([])
const currentSmartRollIndex = ref(0)
const smartRollUserAnswers = ref([])
const showSmartRollAnswer = ref(false)
const smartRollAnswerCorrect = ref(false)
const smartRollCreativeAnswer = ref('')

// 计时器相关状态，删除未使用的 endTime
// const endTime = ref(null)
const startTime = ref(null)

// 得分统计
const score = ref({
  correctCount: 0,
  incorrectCount: 0,
  totalCount: 0,
  percentage: 0,
  timeSpent: 0,
  wrongQuestions: [],
  totalScore: 100,
  scorePerQuestion: 0,
  actualScore: 0
})

// 计算属性
const canSubmit = computed(() => {
  if (currentQuestion.value.type === '创新实践') return creativeAnswer.value.trim().length > 0
  return userAnswers.value.length > 0
})

const isLastQuestion = computed(() => {
  return currentQuestionIndex.value === currentQuestions.value.length - 1
})

const answerFeedback = computed(() => {
  if (!showAnswer.value) return ''
  if (answerCorrect.value) return '回答正确！'
  return `回答错误！正确答案是：${formatAnswer(currentQuestion.value)}`
})

// 智能组卷计算属性
const currentSmartRollQuestion = computed(() => {
  return smartRollQuestions.value[currentSmartRollIndex.value] || {}
})

const canSubmitSmartRoll = computed(() => {
  if (currentSmartRollQuestion.value.type === '创新实践') {
    return smartRollCreativeAnswer.value.trim().length > 0
  }
  return smartRollUserAnswers.value.length > 0
})

const isLastSmartRollQuestion = computed(() => {
  return currentSmartRollIndex.value === smartRollQuestions.value.length - 1
})

const smartRollAnswerFeedback = computed(() => {
  if (!showSmartRollAnswer.value) return ''
  if (smartRollAnswerCorrect.value) return '回答正确！'
  return `回答错误！正确答案是：${formatSmartRollAnswer(currentSmartRollQuestion.value)}`
})

// 创新思维与开发课程章节数据
const chapters = ref([
  {
    name: '创新思维基础',
    total: 15,
    choice: 10,
    judgment: 3,
    creative: 2
  },
  {
    name: '创新方法应用',
    total: 18,
    choice: 12,
    judgment: 3,
    creative: 3
  },
  {
    name: '创新案例解析',
    total: 12,
    choice: 6,
    judgment: 2,
    creative: 4
  }
])

// 过滤章节
const filteredChapters = computed(() => {
  return chapters.value.filter(chapter => 
    chapter.name.toLowerCase().includes(searchQuery.value.toLowerCase())
  )
})

// 所有练习题数据
const allQuestions = {
  '创新思维基础': [
    {
      id: 'q1',
      title: '创新思维的五大特征',
      type: '多选题',
      difficulty: '中等',
      stem: '下列哪些是创新思维的主要特征？',
      options: ['开放性', '独创性', '流畅性', '灵活性', '精确性'],
      answer: '0,1,2,3',
      analysis: '创新思维的特征包括开放性、独创性、流畅性和灵活性，但不包括精确性。'
    },
    {
      id: 'q2',
      title: '创新与创造的区别',
      type: '单选题',
      difficulty: '简单',
      stem: '以下关于创新与创造的区别描述正确的是？',
      options: [
        '创新是产生全新事物，创造是改进现有事物',
        '创新强调实用性，创造强调新颖性',
        '创新是创造的具体应用',
        '创造是创新的前提和基础'
      ],
      answer: '3',
      analysis: '创造是产生全新思想或事物的过程，而创新是将创造性想法转化为实际应用的过程。'
    },
    {
      id: 'q3',
      title: '突破性创新',
      type: '判断题',
      difficulty: '简单',
      stem: '突破性创新是指对现有产品或服务进行渐进式改进的创新方式。',
      answer: 'false',
      analysis: '突破性创新是指打破现有模式和框架的全新创新，不同于渐进式改进。'
    },
    {
      id: 'q4',
      title: '创新思维应用',
      type: '创新实践',
      difficulty: '困难',
      stem: '请设计一种解决校园垃圾分类问题的新方法，要求不同于现有方法。',
      answer: '',
      analysis: '评估要点：1. 新颖性 2. 实用性 3. 可行性 4. 创新程度'
    }
  ],
  '创新方法应用': [
    {
      id: 'q5',
      title: '头脑风暴法的核心原则',
      type: '单选题',
      difficulty: '简单',
      stem: '以下哪项是头脑风暴法的核心原则？',
      options: ['追求质量', '延迟评判', '个人主导', '严格筛选'],
      answer: '1',
      analysis: '延迟评判是头脑风暴的核心原则，确保参与者能自由表达想法而不被批评。'
    }
  ],
  '创新案例解析': [
    {
      id: 'q8',
      title: '创新案例分析',
      type: '创新实践',
      difficulty: '困难',
      stem: '分析特斯拉公司的创新策略，并提出可以改进的建议。',
      answer: '',
      analysis: '评估要点：1. 分析深度 2. 建议创新性 3. 可实现性'
    }
  ]
}

// 开始章节练习
const startChapterPractice = (chapter) => {
  currentChapter.value = chapter.name
  currentQuestions.value = allQuestions[chapter.name] || []
  currentQuestionIndex.value = 0
  showQuestionPractice.value = true
  showScore.value = false
  resetPracticeState()
}

// 返回到章节列表
const backToChapters = () => {
  showQuestionPractice.value = false
  showSmartRoll.value = false
  showScore.value = false
}

// 当前显示的题目
const currentQuestion = computed(() => {
  return currentQuestions.value[currentQuestionIndex.value] || {}
})

// 选择选项
const selectOption = (index) => {
  if (showAnswer.value) return // 已显示答案时不能修改选项

  if (currentQuestion.value.type === '单选题') {
    userAnswers.value = [index]
  } else if (currentQuestion.value.type === '多选题') {
    const existingIndex = userAnswers.value.indexOf(index)
    if (existingIndex === -1) {
      userAnswers.value.push(index)
    } else {
      userAnswers.value.splice(existingIndex, 1)
    }
  }
}

// 选择智能组卷选项
const selectSmartRollOption = (index) => {
  if (showSmartRollAnswer.value) return

  if (currentSmartRollQuestion.value.type === '单选题') {
    smartRollUserAnswers.value = [index]
  } else if (currentSmartRollQuestion.value.type === '多选题') {
    const existingIndex = smartRollUserAnswers.value.indexOf(index)
    if (existingIndex === -1) {
      smartRollUserAnswers.value.push(index)
    } else {
      smartRollUserAnswers.value.splice(existingIndex, 1)
    }
  }
}

// 选择判断题答案
const selectJudgment = (value) => {
  if (showAnswer.value) return // 已显示答案时不能修改选项
  userAnswers.value = [value]
}

// 选择智能组卷判断题答案
const selectSmartRollJudgment = (value) => {
  if (showSmartRollAnswer.value) return
  smartRollUserAnswers.value = [value]
}

// 检查答案
const checkAnswer = () => {
  if (currentQuestion.value.type === '创新实践') {
    showAnswer.value = true
    answerCorrect.value = true // 实践题不自动判断正确与否
    return
  }

  // 检查答案是否正确
  let isCorrect = false

  if (currentQuestion.value.type === '单选题' || currentQuestion.value.type === '判断题') {
    isCorrect = userAnswers.value[0]?.toString() === currentQuestion.value.answer
  } else if (currentQuestion.value.type === '多选题') {
    const correctAnswers = currentQuestion.value.answer.split(',').sort()
    const userAnswerSorted = [...userAnswers.value].sort().map(String)
    isCorrect = correctAnswers.length === userAnswerSorted.length &&
    correctAnswers.every((val, index) => val === userAnswerSorted[index])
  }

  answerCorrect.value = isCorrect
  showAnswer.value = true

  // 如果回答错误，将题目添加到错题列表
  if (!isCorrect) {
    score.value.wrongQuestions.push({
      ...currentQuestion.value,
      userAnswer: userAnswers.value
    })
  }
}

// 检查智能组卷答案
const checkSmartRollAnswer = () => {
  if (currentSmartRollQuestion.value.type === '创新实践') {
    showSmartRollAnswer.value = true
    smartRollAnswerCorrect.value = true // 实践题不自动判断正确与否
    return
  }

  // 检查答案是否正确
  let isCorrect = false

  if (currentSmartRollQuestion.value.type === '单选题' || currentSmartRollQuestion.value.type === '判断题') {
    isCorrect = smartRollUserAnswers.value[0]?.toString() === currentSmartRollQuestion.value.answer
  } else if (currentSmartRollQuestion.value.type === '多选题') {
    const correctAnswers = currentSmartRollQuestion.value.answer.split(',').sort()
    const userAnswerSorted = [...smartRollUserAnswers.value].sort().map(String)
    isCorrect = correctAnswers.length === userAnswerSorted.length &&
    correctAnswers.every((val, index) => val === userAnswerSorted[index])
  }

  smartRollAnswerCorrect.value = isCorrect
  showSmartRollAnswer.value = true

  // 如果回答错误，将题目添加到错题列表
  if (!isCorrect) {
    score.value.wrongQuestions.push({
      ...currentSmartRollQuestion.value,
      userAnswer: smartRollUserAnswers.value
    })
  }
}




// 总结弹窗相关状态
const showSummary = ref(false)

// 复习错题方法
const reviewWrongQuestions = () => {
  // 这里可以添加复习错题的逻辑
  console.log('开始复习错题')
}

// 完成练习并返回方法
const finishAndReturn = () => {
  showSummary.value = false
  backToChapters()
}
// // 计算得分
// const calculateScore = () => {
//   score.value.actualScore = score.value.correctCount * score.value.scorePerQuestion
//   score.value.percentage = Math.round((score.value.actualScore / score.value.totalScore) * 100)
// }

// 重置练习状态
const resetPracticeState = () => {
  userAnswers.value = []
  showAnswer.value = false
  answerCorrect.value = false
  creativeAnswer.value = ''
}

// 重置智能组卷状态
const resetSmartRollState = () => {
  smartRollUserAnswers.value = []
  showSmartRollAnswer.value = false
  smartRollAnswerCorrect.value = false
  smartRollCreativeAnswer.value = ''
}

// 格式化答案显示
const formatAnswer = (question) => {
  if (!question) return ''

  if (question.type === '多选题' && question.answer.includes(',')) {
    return question.answer.split(',').map(a => String.fromCharCode(65 + parseInt(a))).join(', ')
  }
  if (question.type === '单选题') {
    return String.fromCharCode(65 + parseInt(question.answer))
  }
  if (question.type === '判断题') {
    return question.answer === 'true' ? '正确' : '错误'
  }
  return question.answer
}

// 格式化用户答案
const formatUserAnswer = (userAnswer, type) => {
  if (type === '多选题') {
    return userAnswer.map(index => String.fromCharCode(65 + index)).join(', ')
  } else if (type === '判断题') {
    return userAnswer === 'true' ? '正确' : '错误'
  } else {
    return String.fromCharCode(65 + userAnswer)
  }
}


// 格式化智能组卷答案显示
const formatSmartRollAnswer = (question) => {
  if (!question) return ''
  return formatAnswer(question)
}

// 格式化时间显示
const formatTime = (seconds) => {
  const mins = Math.floor(seconds / 60)
  const secs = seconds % 60
  return (mins > 0 ? mins + '分' : '') + secs + '秒'
}

// 重新开始智能组卷
const restartSmartRoll = () => {
  showScore.value = false
  smartRoll()
}

// 智能组卷
const smartRoll = () => {
  const selectedQuestions = []
  const questionTypes = ['单选题', '多选题', '判断题', '创新实践']
  let typesCovered = new Set()

  Object.keys(allQuestions).forEach(chapter => {
    const questions = allQuestions[chapter]
    // 按题型分类
    const questionsByType = {}
    questions.forEach(q => {
      if (!questionsByType[q.type]) {
        questionsByType[q.type] = []
      }
      questionsByType[q.type].push(q)
    })
    // 每种题型最多选1题
    questionTypes.forEach(type => {
      if (questionsByType[type]?.length > 0) {
        const randomIndex = Math.floor(Math.random() * questionsByType[type].length)
        const selectedQ = questionsByType[type][randomIndex]
        selectedQuestions.push(selectedQ)
        typesCovered.add(type)
      }
    })
  })

  // 确保每种类型题目都有
  questionTypes.forEach(type => {
    if (!typesCovered.has(type)) {
      const chapter = Object.keys(allQuestions)[0]
      const questions = allQuestions[chapter]
      const question = questions.find(q => q.type === type)
      if (question) {
        selectedQuestions.push(question)
      }
    }
  })

  // 随机打乱题目顺序
  smartRollQuestions.value = selectedQuestions
    .sort(() => Math.random() - 0.5)
    .slice(0, 10)  // 最多10题

  currentSmartRollIndex.value = 0
  resetSmartRollState()
  showSmartRoll.value = true
  showScore.value = false

  // 重置得分统计
  score.value = {
    correctCount: 0,
    incorrectCount: 0,
    totalCount: smartRollQuestions.value.length,
    percentage: 0,
    timeSpent: 0,
    wrongQuestions: [],
    totalScore: 100,
    scorePerQuestion: Math.round(100 / smartRollQuestions.value.length), // 计算每题分数，四舍五入
    actualScore: 0
  }

  startTime.value = new Date() // 开始计时
}

// 格式化正确答案
const formatCorrectAnswer = (question) => {
  if (!question) return ''
  let answer = question.answer

  // 如果 answer 是字符串且包含逗号，转换为数组
  if (typeof answer === 'string' && answer.includes(',')) {
    answer = answer.split(',')
  }

  if (question.type === '多选题' && Array.isArray(answer)) {
    return answer.map(index => String.fromCharCode(65 + parseInt(index))).join('，')
  }
  if (question.type === '单选题') {
    return String.fromCharCode(65 + parseInt(answer))
  }
  if (question.type === '判断题') {
    return answer === 'true' ? '正确' : '错误'
  }
  return answer
}

onMounted(() => {
  if (route.query.courseName) {
    currentCourse.value = route.query.courseName
  }
})
// 下一题
const nextQuestion = () => {
  if (isLastQuestion.value) {
    // 计算得分等逻辑
    score.value.correctCount = currentQuestions.value.length - score.value.wrongQuestions.length
    score.value.incorrectCount = score.value.wrongQuestions.length
    score.value.totalCount = currentQuestions.value.length
    score.value.percentage = Math.round((score.value.correctCount / score.value.totalCount) * 100)
    score.value.actualScore = Math.round((score.value.correctCount / score.value.totalCount) * score.value.totalScore)

    showSummary.value = true
  } else {
    currentQuestionIndex.value++
    showAnswer.value = false
    userAnswers.value = []
    creativeAnswer.value = ''
  }
}

// 智能组卷下一题
const nextSmartRollQuestion = () => {
  if (isLastSmartRollQuestion.value) {
    // 计算得分等逻辑
    score.value.correctCount = smartRollQuestions.value.length - score.value.wrongQuestions.length
    score.value.incorrectCount = score.value.wrongQuestions.length
    score.value.totalCount = smartRollQuestions.value.length
    score.value.percentage = Math.round((score.value.correctCount / score.value.totalCount) * 100)
    score.value.actualScore = Math.round((score.value.correctCount / score.value.totalCount) * score.value.totalScore)

    showSummary.value = true
  } else {
    currentSmartRollIndex.value++
    showSmartRollAnswer.value = false
    smartRollUserAnswers.value = []
    smartRollCreativeAnswer.value = ''
  }
}
</script>

<style scoped>
.practice-graph {
  padding: 2rem;
  background-color: #1a1a1a;
  min-height: calc(100vh - 70px);
  color: white;
}

/* 标题部分样式 */
.header-section {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 2rem;
}

.header-section h1 {
  font-family: 'Noto Sans SC', sans-serif;
  font-weight: 700;
  font-size: 24px;
  color: white;
}

.search-filter {
  display: flex;
  gap: 1rem;
  margin-bottom: 1.5rem;
}

.search-input {
  flex: 1;
  padding: 0.75rem;
  border-radius: 6px;
  border: 1px solid #444;
  background: #252525;
  color: white;
}

/* 表格样式 */
.table-container {
  background: #252525;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 1rem;
}

table {
  width: 100%;
  border-collapse: collapse;
}

th {
  background: #333;
  padding: 1rem;
  text-align: left;
  font-family: 'Noto Sans SC', sans-serif;
  font-weight: 500;
}

td {
  padding: 1rem;
  border-bottom: 1px solid #333;
  font-family: 'Noto Sans SC', sans-serif;
  font-weight: 400;
}

/* 按钮样式 */
.practice-btn {
  padding: 0.5rem 1rem;
  border-radius: 4px;
  border: none;
  cursor: pointer;
  font-family: 'Noto Sans SC', sans-serif;
  font-weight: 500;
  background: #3b82f6;
  color: white;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

.back-btn {
  background: transparent;
  color: white;
  border: none;
  cursor: pointer;
  font-size: 1.5rem;
  margin-right: 1rem;
}

.smart-roll-btn {
  padding: 0.5rem 1rem;
  border-radius: 4px;
  border: none;
  cursor: pointer;
  font-family: 'Noto Sans SC', sans-serif;
  font-weight: 500;
  background: #3b82f6;
  color: white;
  display: flex;
  align-items: center;
  gap: 0.5rem;
}

/* 练习界面样式 */
.question-practice {
  max-width: 800px;
  margin: 0 auto;
}

.practice-stats {
  font-family: 'Noto Sans SC', sans-serif;
  color: #aaa;
}

.question-container {
  margin-top: 2rem;
}

.question-card {
  background: #252525;
  border-radius: 12px;
  padding: 2rem;
  box-shadow: 0 4px 12px rgba(0,0,0.2);
}

.question-meta {
  display: flex;
  gap: 1rem;
  margin-bottom: 1rem;
}

.question-type {
  background: #3b82f6;
  color: white;
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.875rem;
}

.question-difficulty {
  padding: 0.25rem 0.5rem;
  border-radius: 4px;
  font-size: 0.875rem;
}

.question-difficulty.简单 {
  background: #10b981;
}

.question-difficulty.中等 {
  background: #f59e0b;
}

.question-difficulty.困难 {
  background: #ef4444;
}

.question-title {
  font-size: 1.2rem;
  margin-bottom: 1.5rem;
  color: #8b5cf6;
}

.question-stem {
  margin-bottom: 2rem;
  line-height: 1.6;
}

/* 选项样式 */
.question-options {
  margin: 1.5rem 0;
}

.option {
  display: flex;
  align-items: center;
  padding: 1rem;
  margin-bottom: 0.75rem;
  background: #333;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.2s;
}

.option:hover:not(.selected, .correct, .incorrect) {
  background: #444;
}

.option.selected {
  background: #3b82f6;
}

.option.correct {
  background: #10b981;
}

.option.incorrect {
  background: #ef4444;
  opacity: 0.7;
}

.option-letter {
  font-weight: bold;
  margin-right: 1rem;
  width: 1.5rem;
}

/* 判断题样式 */
.judgment-options {
  display: flex;
  gap: 1rem;
  margin: 1.5rem 0;
}

.judgment-btn {
  padding: 1rem 1.5rem;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-weight: 500;
  flex: 1;
}

.true-btn {
  background: #333;
  color: white;
}

.true-btn.selected {
  background: #4CAF50;
}

.false-btn.selected {
  background: #F44336;
}

.true-btn.correct {
  background: #4CAF50;
}

.false-btn.correct {
  background: #F44336;
}

.true-btn.incorrect {
  background: #F44336;
  opacity: 0.7;
}

.false-btn.incorrect {
  background: #4CAF50;
  opacity: 0.7;
}

/* 创新实践解答框样式 */
.creative-answer {
  margin: 1.5rem 0;
}

.creative-textarea {
  width: 100%;
  min-height: 150px;
  padding: 1rem;
  border-radius: 6px;
  background: #333;
  color: white;
  border: 1px solid #444;
  resize: vertical;
}

/* 反馈信息样式 */
.answer-feedback {
  margin: 1rem 0;
  padding: 1rem;
  border-radius: 6px;
  font-weight: bold;
  text-align: center;
}

.answer-feedback.correct {
  background-color: rgba(16, 185, 129, 0.2);
  color: #10b981;
}

.answer-feedback.incorrect {
  background-color: rgba(239, 68, 68, 0.2);
  color: #ef4444;
}

/* 答案解析样式 */
.answer-analysis {
  margin: 1.5rem 0;
  padding: 1.5rem;
  background: rgba(59, 130, 246, 0.1);
  border-radius: 8px;
  border-left: 4px solid #3b82f6;
}

.analysis-title {
  font-weight: bold;
  margin-bottom: 0.5rem;
  color: #3b82f6;
}

.analysis-content {
  line-height: 1.6;
}

/* 练习操作按钮 */
.practice-actions {
  display: flex;
  justify-content: center;
  margin-top: 2rem;
}

.submit-btn, .next-btn {
  padding: 0.75rem 2rem;
  border: none;
  border-radius: 6px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
}

.submit-btn {
  background: #3b82f6;
  color: white;
}

.submit-btn:hover:not(:disabled) {
  background: #2563eb;
}

.submit-btn:disabled {
  background: #444;
  cursor: not-allowed;
  opacity: 0.6;
}

.next-btn {
  background: #8b5cf6;
  color: white;
}

.next-btn:hover {
  background: #7c3aed;
}

/* 智能组卷界面样式 */
.smart-roll {
  max-width: 800px;
  margin: 0 auto;
}

.smart-roll-container {
  background: #252525;
  border-radius: 12px;
  padding: 2rem;
  box-shadow: 0 4px 12px rgba(0,0,0.2);
}

.smart-roll-card {
  background: #333;
  border-radius: 8px;
  margin-bottom: 1rem;
  padding: 1rem;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .practice-graph {
    padding: 1rem;
  }

  .header-section {
    flex-direction: column;
    align-items: flex-start;
    gap: 1rem;
  }

  .question-card {
    padding: 1rem;
  }

  .judgment-options {
    flex-direction: column;
  }

  .practice-actions {
    flex-direction: column;
    gap: 1rem;
  }

  .submit-btn, .next-btn {
    width: 100%;
  }
}
.score-container {
  max-width: 800px;
  margin: 0 auto;
}
.score-card {
  background: #252525;
  border-radius: 12px;
  padding: 2rem;
  box-shadow: 0 4px 12px rgba(0,0,0,0.2);
  text-align: center;
  margin-bottom: 2rem;
}
.score-card h2 {
  font-size: 1.5rem;
  margin-bottom: 1.5rem;
  color: #8b5cf6;
}
.score-main {
  display: flex;
  justify-content: space-around;
  align-items: center;
  margin-bottom: 2rem;
}
.score-circle {
  width: 150px;
  height: 150px;
  border-radius: 50%;
  background: linear-gradient(135deg, #3b82f6, #8b5cf6);
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
}
.score-value {
  font-size: 2rem;
  font-weight: bold;
  margin-bottom: 0.5rem;
}
.score-percentage {
  font-size: 1.25rem;
  margin-bottom: 0.5rem;
}
.score-per-question {
  font-size: 0.75rem;
  opacity: 0.8;
}
.score-details {
  flex: 1;
  padding-left: 2rem;
  text-align: left;
}
.detail-item {
  margin-bottom: 0.75rem;
}
.detail-label {
  display: inline-block;
  width: 80px;
  font-weight: bold;
}
.detail-value {
  font-weight: bold;
}
.detail-value.correct {
  color: #10b981;
}
.detail-value.incorrect {
  color: #ef4444;
}
.restart-btn, .back-home-btn {
  padding: 0.75rem 1.5rem;
  border: none;
  border-radius: 6px;
  font-size: 1rem;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.2s;
  margin: 0 0.5rem;
}
.restart-btn {
  background: #3b82f6;
  color: white;
}
.restart-btn:hover {
  background: #2563eb;
}
.back-home-btn {
  background: #444;
  color: white;
}
.back-home-btn:hover {
  background: #555;
}
.mistakes-section {
  margin-top: 2rem;
  background: #333;
  border-radius: 8px;
  padding: 1rem;
  box-shadow: 0 4px 12px rgba(0,0,0.2);
}

.mistake-item {
  border-bottom: 1px solid #444;
  padding: 1rem 0;
}

.mistake-header {
  display: flex;
  justify-content: space-between;
  font-weight: bold;
  margin-bottom: 0.5rem;
}

.mistake-index {
  color: #3b82f6;
}

.mistake-percentage {
  color: #8b5cf6;
}

.mistake-content {
  display: flex;
  flex-direction: column;
}

.mistake-question {
  font-size: 1rem;
  margin-bottom: 0.5rem;
  color: #ef4444;
}

.mistake-answer {
  display: flex;
  justify-content: space-between;
}

.wrong-answer {
  color: #ef4444;
}

.correct-answer {
  color: #10b981;
}
/* 练习总结弹窗样式 */
.summary-modal { 
  position: fixed; 
  top: 0; 
  left: 0; 
  right: 0; 
  bottom: 0; 
  display: flex; 
  justify-content: center; 
  align-items: center; 
  z-index: 1000; 
} 

.modal-overlay { 
  position: absolute; 
  width: 100%; 
  height: 100%; 
  background: rgba(0, 0, 0, 0.7); 
  backdrop-filter: blur(5px); 
} 

.modal-content { 
  background: #1e1e1e; 
  border-radius: 16px; 
  padding: 30px; 
  width: 90%; 
  max-width: 600px; 
  max-height: 80vh; 
  overflow-y: auto; 
  position: relative; 
  border: 1px solid rgba(139, 92, 246, 0.3); 
} 

.modal-content h2 { 
  color: #8b5cf6; 
  text-align: center; 
  margin-top: 0; 
} 

.stats-container { 
  display: flex; 
  justify-content: space-around; 
  margin: 30px 0; 
} 

.stat-item { 
  text-align: center; 
} 

.stat-value { 
  font-size: 28px; 
  font-weight: bold; 
  margin-bottom: 5px; 
} 

.stat-label { 
  color: #aaa; 
  font-size: 14px; 
} 

.mistakes-section { 
  margin-top: 30px; 
} 

.mistakes-section h3 { 
  color: #8b5cf6; 
  border-bottom: 1px solid #333; 
  padding-bottom: 10px; 
} 

.mistake-item { 
  background: #252525; 
  border-radius: 8px; 
  padding: 15px; 
  margin: 10px 0; 
} 

.mistake-question { 
  margin-bottom: 8px; 
} 

.mistake-answer { 
  display: flex; 
  flex-direction: column; 
  gap: 5px; 
} 

.wrong-answer { 
  color: #ef4444; 
} 

.correct-answer { 
  color: #10b981; 
} 

.modal-actions { 
  display: flex; 
  justify-content: center; 
  gap: 15px; 
  margin-top: 30px; 
} 

.action-btn {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  padding: 10px 20px;
  border-radius: 8px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
  border: none;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
  
  .material-icons {
    margin-right: 8px;
    font-size: 20px;
  }
  
  &:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0,0,0,0.15);
  }
  
  &:active {
    transform: translateY(0);
  }
}

.review-btn {
  background: linear-gradient(135deg, #3b82f6, #2563eb);
  color: white;
  
  &:hover {
    background: linear-gradient(135deg, #2563eb, #1d4ed8);
  }
}

.finish-btn {
  background: linear-gradient(135deg, #10b981, #059669);
  color: white;
  
  &:hover {
    background: linear-gradient(135deg, #059669, #047857);
  }
} 

/* 响应式设计 */ 
@media (max-width: 768px) { 
  .practice-header { 
    flex-direction: column; 
    gap: 15px; 
  } 

  .back-btn { 
    align-self: flex-start; 
  } 

  .header-title { 
    order: 2; 
  } 

  .timer { 
    order: 1; 
    align-self: flex-end; 
  } 

  .modal-actions { 
    flex-direction: column; 
  } 

  .modal-actions button { 
    width: 100%; 
  } 
} 
</style>